package com.memory.modules.business.service.sell.impl;

import com.memory.common.data.PageSort;
import com.memory.common.exception.ResultException;
import com.memory.modules.business.domain.sell.InvoiceRecord;
import com.memory.modules.business.repository.sell.InvoiceRecordRepository;
import com.memory.modules.business.service.sell.InvoiceRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @PackageName: com.memory.modules.business.service.sell.impl
 * @ClassName: InvoiceRecordServiceImpl
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/13
 */
@Service
@RequiredArgsConstructor
public class InvoiceRecordServiceImpl implements InvoiceRecordService {

    private final InvoiceRecordRepository invoiceRecordRepository;

    @Override
    public InvoiceRecord create(InvoiceRecord record) {
        return invoiceRecordRepository.save(record);
    }

    @Override
    public InvoiceRecord modify(Long id, InvoiceRecord record) {
        return findById(id).map(e -> {
            record.setId(id);
            invoiceRecordRepository.save(record);
            return e;
        }).orElseThrow(() -> new ResultException(500, ""));
    }

    @Override
    public Optional<InvoiceRecord> findById(Long id) {
        return invoiceRecordRepository.findById(id);
    }

    @Override
    public InvoiceRecord remove(Long id) {
        return findById(id).map(e -> {
            invoiceRecordRepository.delete(e);
            return e;
        }).orElseThrow(() -> new ResultException(500, ""));
    }

    @Override
    public Page<InvoiceRecord> findPage(Example<InvoiceRecord> example) {
        final PageRequest pageRequest = PageSort.pageRequest();
        return invoiceRecordRepository.findAll(example, pageRequest);
    }
}
